package com.alibaba.csp.sentinel.demo.slot;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreakerStrategy;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

public class SentinelRuleDefine {
	
 	 private static String KEY="ERROR_RATIO";
	 static void defineRule() {
		 initDegradeRule();
		 initFlowQpsRule();
	 }

	public static void initDegradeRule() {
	        List<DegradeRule> rules = new ArrayList<>();
	        DegradeRule rule = new DegradeRule(KEY)
	            .setGrade(CircuitBreakerStrategy.ERROR_RATIO.getType())
	            // Set ratio threshold to 50%.
	            .setCount(0.1d)
	            .setStatIntervalMs(1000)
	            .setMinRequestAmount(3)
	            // Retry timeout (in second)
	            .setTimeWindow(10);
	        rules.add(rule);
	        DegradeRuleManager.loadRules(rules);
	        System.out.println("Degrade rule loaded: " + rules);
	      
	        
	    }
	 
	 
	  private static void initFlowQpsRule() {
	        List<FlowRule> rules = new ArrayList<FlowRule>();
	        FlowRule rule1 = new FlowRule();
	        rule1.setResource(KEY);
	        // set limit qps to 20
	        rule1.setCount(1);
	        rule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
	        rule1.setLimitApp("default");
	        rules.add(rule1);
	        FlowRuleManager.loadRules(rules);
	    }
	  
}
